import os
import shutil
import pandas as pd

def process_folders(root_dir):
    """
    遍历指定根目录，查找包含'processed'的文件夹，并处理其中的CSV文件。
    """
    for dirpath, dirnames, filenames in os.walk(root_dir):
        if "processed" in os.path.basename(dirpath).lower():
            print(f"找到 processed 文件夹: {dirpath}")
            
            # 定义源文件夹和目标文件夹名称
            source_folder_name = "1000f2.4ms"
            target_folder_name = "1000f2.2ms"
            reference_folder_name = "1000f2.0ms"

            source_path = os.path.join(dirpath, source_folder_name)
            target_path = os.path.join(dirpath, target_folder_name)
            reference_path = os.path.join(dirpath, reference_folder_name)

            # 检查源文件夹是否存在
            if not os.path.exists(source_path):
                print(f"警告: 在 {dirpath} 中未找到 {source_folder_name} 文件夹，跳过。")
                continue

            # 1. 复制 1000f2.4ms 文件夹到 1000f2.2ms
            if os.path.exists(target_path):
                shutil.rmtree(target_path) # 如果目标文件夹已存在，先删除
                print(f"已删除现有文件夹: {target_path}")
            
            shutil.copytree(source_path, target_path)
            print(f"已将 {source_path} 复制到 {target_path}")

            # 2. 处理 1000f2.2ms 文件夹中的 CSV 文件
            if not os.path.exists(reference_path):
                print(f"警告: 在 {dirpath} 中未找到 {reference_folder_name} 文件夹，无法计算平均值，跳过CSV处理。")
                continue

            for filename in os.listdir(target_path):
                if filename.endswith(".csv"):
                    target_csv_path = os.path.join(target_path, filename)
                    source_csv_path = os.path.join(source_path, filename)
                    reference_csv_path = os.path.join(reference_path, filename)

                    if not os.path.exists(source_csv_path):
                        print(f"警告: 在 {source_path} 中未找到 {filename}，跳过此CSV文件。")
                        continue
                    if not os.path.exists(reference_csv_path):
                        print(f"警告: 在 {reference_path} 中未找到 {filename}，跳过此CSV文件。")
                        continue

                    try:
                        df_target = pd.read_csv(target_csv_path)
                        df_source = pd.read_csv(source_csv_path)
                        df_reference = pd.read_csv(reference_csv_path)

                        # 确保所有DataFrame的形状相同
                        if not (df_target.shape == df_source.shape == df_reference.shape):
                            print(f"警告: CSV文件 {filename} 在不同文件夹中形状不匹配，跳过。")
                            continue

                        # 计算平均值 (1000f2.4ms 和 1000f2.0ms 的平均值)
                        df_averaged = (df_source + df_reference) / 2

                        # 将平均值写入 1000f2.2ms 文件夹中的 CSV 文件
                        df_averaged.to_csv(target_csv_path, index=False)
                        print(f"已更新 {target_csv_path} 中的CSV数据为平均值。")

                    except Exception as e:
                        print(f"处理CSV文件 {filename} 时发生错误: {e}")

if __name__ == "__main__":
    # 请将此路径更改为您的实际根目录
    root_directory = r"J:\lqb\huanxingranliao" 
    
    # 检查pandas是否安装
    try:
        import pandas as pd
    except ImportError:
        print("错误: pandas库未安装。请运行 'pip install pandas' 安装。")
        exit()

    if not os.path.exists(root_directory):
        print(f"错误: 指定的根目录 '{root_directory}' 不存在。请检查路径。")
    else:
        process_folders(root_directory)
        print("脚本执行完毕。")
